import { State as RootState } from "@/store/root"
import { cart, checkout, order, shipping } from "@mall/api-services"

import BigDecimal from "decimal.js"
import * as _ from "lodash"
import { ActionContext, Module } from "vuex"

class CheckoutState {
  id = ""
  cartId = ""
  shippingAddress: shipping.Address = new shipping.Address()
  orders: order.Order[] = []
}

const state = () => new CheckoutState()

const getters = {
  totalPrice: (state: CheckoutState) => {
    return _.chain(state.orders)
      .reduce((total: number, aOrder: order.Order) => {
        const total2 = BigDecimal.add(total, aOrder.totalAmount).toNumber()
        console.log(total2)
        return total2
      }, 0)
      .value()
  },
}
const mutations = {
  setCheckout(state: CheckoutState, aCheckout: checkout.Checkout) {
    state.id = aCheckout.id
    state.shippingAddress = aCheckout.shippingAddress
    state.orders = aCheckout.orders
  },
}

const actions = {
  setItems({ commit }: ActionContext<CheckoutState, RootState>, items: cart.CartItem[]) {
    commit("setItems", items)
  },

  refresh({ commit }: ActionContext<CheckoutState, RootState>, id: string) {
    return checkout.CheckoutServiceV1.getCheckout(id)
      .then(aCheckout => {
        commit("setCheckout", aCheckout)
      })
  },
  changeShippingAddress({ commit, state }: ActionContext<CheckoutState, RootState>, shippingAddress: shipping.Address) {
    const aCheckout = new checkout.Checkout()
    aCheckout.id = state.id
    aCheckout.shippingAddress = shippingAddress
    return checkout.CheckoutServiceV1.updateCheckout(aCheckout)
      .then(savedCheckout => commit("setCheckout", savedCheckout))
  },
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations,
} as Module<CheckoutState, RootState>
